// allocation-manage.js
const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')
Page({
  data: {
    allocationList: [],
    orderList: [],
    statusList: ['全部', '待完成', '已报工', '已完成'],
    statusIndex: 0,
    orderIndex: -1,
    page: 1,
    limit: 10,
    hasMore: true,
    loading: false,
    // 权限相关数据
    hasViewPermission: false,
    hasAddPermission: false,
    hasEditPermission: false,
    hasDeletePermission: false,
    hasBatchPermission: false
  },

  onLoad() {
    // 页面权限检查
    console.log('allocation-manage onLoad - 开始权限检查');
    if (!pagePermission.requirePagePermission('pages/allocation-manage/allocation-manage')) {
      console.log('allocation-manage onLoad - 权限检查失败，退出');
      return
    }
    console.log('allocation-manage onLoad - 权限检查通过');
    
    // 检查并设置页面权限状态
    this.checkPermissions()
    
    this.loadOrders()
    this.loadAllocations()
  },

  onShow() {
    this.refreshAllocations()
  },

  // 加载订单列表
  loadOrders() {
    api.getOrders().then(res => {
      this.setData({
        orderList: res.data.list || []
      })
    }).catch(err => {
      console.error('加载订单失败:', err)
    })
  },

  // 加载分工列表
  loadAllocations() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    const params = {
      page: this.data.page,
      limit: this.data.limit
    }
    
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusIndex - 1
    }
    
    if (this.data.orderIndex >= 0) {
      params.order_id = this.data.orderList[this.data.orderIndex].id
    }
    
    api.getAllocations(params).then(res => {
      const newList = this.data.page === 1 ? res.data.list : [...this.data.allocationList, ...res.data.list]
      
      // 格式化时间
      newList.forEach(item => {
        item.createtime_text = this.formatTime(item.createtime)
      })
      
      this.setData({
        allocationList: newList,
        hasMore: res.data.list.length === this.data.limit,
        loading: false
      })
    }).catch(err => {
      this.setData({ loading: false })
      console.error('加载分工列表失败:', err)
    })
  },

  // 刷新分工列表
  refreshAllocations() {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadAllocations()
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadAllocations()
    }
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: e.detail.value,
      page: 1,
      hasMore: true
    })
    this.loadAllocations()
  },

  // 订单筛选
  onOrderChange(e) {
    this.setData({
      orderIndex: e.detail.value,
      page: 1,
      hasMore: true
    })
    this.loadAllocations()
  },

  // 跳转到创建分工页面
  goToCreateAllocation() {

    
    wx.navigateTo({
      url: '/pages/create-allocation/create-allocation'
    })
  },

  // 批量分工
  batchCreate() {

    
    wx.showModal({
      title: '批量分工',
      content: '此功能将根据订单自动分配任务给员工',
      success: (res) => {
        if (res.confirm) {
          // 这里可以实现批量分工逻辑
          wx.showToast({
            title: '批量分工功能开发中',
            icon: 'none'
          })
        }
      }
    })
  },

  // 编辑分工
  editAllocation(e) {
    if (!this.hasPermission('allocation_manage', 'edit')) {
      wx.showToast({
        title: '您没有编辑权限',
        icon: 'none'
      })
      return
    }
    
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/create-allocation/create-allocation?id=${id}`
    })
  },

  // 删除分工
  deleteAllocation(e) {

    
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个分工任务吗？',
      success: (res) => {
        if (res.confirm) {
          // 这里调用删除API
          wx.showToast({
            title: '删除功能开发中',
            icon: 'none'
          })
        }
      }
    })
  },

  // 格式化时间
  formatTime(timestamp) {
    const date = new Date(timestamp * 1000)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshAllocations()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadMore()
  },

  // 导航方法
  goToIndex() {
    console.log('点击了首页导航')
    wx.navigateTo({
      url: '/pages/index/index',
      success: () => {
        console.log('跳转到首页成功')
      },
      fail: (err) => {
        console.error('跳转到首页失败:', err)
      }
    })
  },

  goToReports() {
    console.log('点击了报工管理导航')
    wx.navigateTo({
      url: '/pages/reports/reports',
      success: () => {
        console.log('跳转到报工管理成功')
      },
      fail: (err) => {
        console.error('跳转到报工管理失败:', err)
      }
    })
  },

  // 检查权限
  checkPermissions() {
    const app = getApp();
    const adminInfo = app.globalData.adminInfo;
    
    console.log('checkPermissions - adminInfo:', adminInfo);
    console.log('checkPermissions - adminInfo.id:', adminInfo ? adminInfo.id : 'null');
    console.log('checkPermissions - adminInfo.id type:', adminInfo ? typeof adminInfo.id : 'null');
    
    if (!adminInfo || !adminInfo.id) {
      console.log('checkPermissions - 没有管理员信息或ID');
      this.setData({
        hasViewPermission: false,
        hasAddPermission: false,
        hasEditPermission: false,
        hasDeletePermission: false,
        hasBatchPermission: false
      });
      return;
    }
    
    // 超级管理员拥有所有权限
    if (adminInfo.id == 1 || adminInfo.id === 1 || adminInfo.id === '1') {
      console.log('checkPermissions - 超级管理员权限设置');
      this.setData({
        hasViewPermission: true,
        hasAddPermission: true,
        hasEditPermission: true,
        hasDeletePermission: true,
        hasBatchPermission: true
      });
      return;
    }
    
    // 检查各项权限
    const hasViewPermission = permissionUtils.hasPermission(adminInfo.id, 'allocation_manage', 'view');
    const hasAddPermission = permissionUtils.hasPermission(adminInfo.id, 'allocation_manage', 'add');
    const hasEditPermission = permissionUtils.hasPermission(adminInfo.id, 'allocation_manage', 'edit');
    const hasDeletePermission = permissionUtils.hasPermission(adminInfo.id, 'allocation_manage', 'delete');
    const hasBatchPermission = permissionUtils.hasPermission(adminInfo.id, 'allocation_manage', 'batch');
    
    console.log('权限检查详情:', {
      adminId: adminInfo.id,
      adminIdType: typeof adminInfo.id,
      hasViewPermission,
      hasAddPermission,
      hasEditPermission,
      hasDeletePermission,
      hasBatchPermission
    });
    
    this.setData({
      hasViewPermission,
      hasAddPermission,
      hasEditPermission,
      hasDeletePermission,
      hasBatchPermission
    });
    
    // 如果没有查看权限，显示提示并返回
    if (!hasViewPermission) {
      console.log('权限检查失败：没有查看权限');
      wx.showToast({
        title: '无权限访问此页面',
        icon: 'none',
        duration: 2000
      });
      
      setTimeout(() => {
        this.goBack();
      }, 2000);
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1,
      fail: () => {
        wx.switchTab({
          url: '/pages/index/index'
        });
      }
    });
  },

  // 检查是否有权限执行某个操作
  hasPermission(module, action) {
    // 从session中获取管理员信息
    const app = getApp();
    const adminInfo = app.globalData.adminInfo;
    if (!adminInfo || !adminInfo.id) {
      return false;
    }
    
    // 使用权限工具检查权限（基于管理组）
    return permissionUtils.hasPermission(adminInfo.id, module, action);
  }
}) 